package com.dense.kuiniu.bookborrow.business.home.back;

import android.content.DialogInterface;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.android.serialport.SerialPortManager;
import com.android.serialport.entity.InventoryBean;
import com.blankj.utilcode.util.LanguageUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.dense.kuiniu.bookborrow.R;
import com.dense.kuiniu.bookborrow.base.BaseFragment;
import com.dense.kuiniu.bookborrow.base.Url;
import com.dense.kuiniu.bookborrow.business.adapter.BookScanAdapter;
import com.dense.kuiniu.bookborrow.business.entity.BorrowResult;
import com.dense.kuiniu.bookborrow.business.entity.QueryBookInfo;
import com.dense.kuiniu.bookborrow.receiver.SystemTTS;
import com.dense.kuiniu.bookborrow.view.CountDownView;
import com.dense.kuiniu.bookborrow.view.CounterController;
import com.dense.kuiniu.bookborrow.view.SpaceItemDecoration;
import com.dense.kuiniu.bookborrow.view.dialog.CommonDialog;
import com.dense.kuiniu.bookborrow.xjSetting.config.ShareKeyConfig;
import com.dense.kuiniu.bookborrow.xjSetting.utils.SharePreferceUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rfid.event.ReadEvent;
import com.rfid.event.WriteEvent;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.functions.Consumer;
import rxhttp.RxHttp;

/**
 * @author Administrator
 * @date 2020/8/11
 */
public class BackScanBookDelegate extends BaseFragment {

    public static BackScanBookDelegate getInstance() {
        return new BackScanBookDelegate();
    }

    @BindView(R.id.count_down_view)
    CountDownView mCountDownView;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_scan_count)
    TextView mTvScanCount;
    @BindView(R.id.tv_choose_count)
    TextView mTvChooseCount;
    @BindView(R.id.cb_all)
    CheckBox mCbAll;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    private Map<String, QueryBookInfo> mSelectedMap = new ConcurrentHashMap<>();
    private BookScanAdapter mScanAdapter;
    private CommonDialog mDialog;
    private Map<String, InventoryBean> mReadMap = new HashMap<>();
    private CountDownLatch mDownLatch;

    @Override
    protected int getLayoutRes() {
        return R.layout.delegate_back_scan_book;
    }

    @Override
    protected void init() {
        if (getActivity() != null) {
            mTvTitle.setText(R.string.text_book_scan);
            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
            mRecyclerView.setAdapter(mScanAdapter = new BookScanAdapter(R.layout.item_book_scan, null));
            mRecyclerView.addItemDecoration(new SpaceItemDecoration(20));
            mScanAdapter.addChildClickViewIds(R.id.checkbox);
            mScanAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    QueryBookInfo bookBean = (QueryBookInfo) adapter.getItem(position);
                    CheckBox checkBox = (CheckBox) view;
                    if (bookBean != null) {
                        bookBean.setChecked(checkBox.isChecked());
                        if (checkBox.isChecked()) {
                            mSelectedMap.put(bookBean.getBookBarCode(), bookBean);
                        } else {
                            mSelectedMap.remove(bookBean.getBookBarCode());
                        }
                        checkIsAll();
                    }
                }
            });
            int second = SharePreferceUtil.getInstance(getContext()).getInt(ShareKeyConfig.ER_JI_CAIDAN, 60);
            mCountDownView.setSeconds(second);
            mCountDownView.start(new CounterController.OnCompleteListener() {
                @Override
                public void onComplete() {
                    exit();
                }
            });
            mTvChooseCount.setText(String.format(LanguageUtils.getCurrentLocale(),
                    "%s%d%s", getString(R.string.text_had_choose), mSelectedMap.size(), getString(R.string.text_book_unit)));
            mTvScanCount.setText(String.format(LanguageUtils.getCurrentLocale(),
                    "%s%d%s", getString(R.string.text_scan), mScanAdapter.getItemCount(), getString(R.string.text_book_unit)));
            EventBus.getDefault().register(this);
            mCbAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkAll(mCbAll.isChecked());
                }
            });
            SystemTTS.getInstance().playText("请将图书放入图书感应区，不要拿走图书");
            SerialPortManager.getInstance().startInventory();
        }
    }

    @OnClick({R.id.tv_return, R.id.tv_return_books})
    public void onClick(View view) {
        super.onClick(view);
    }

    @Override
    public void onClick2(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.tv_return:
                exit();
                break;
            case R.id.tv_return_books:
                returnBook();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReadEvent(ReadEvent event) {
        InventoryBean bean = mReadMap.get(event.mInventoryBean.getBookBarNo());
        if (bean == null) {
            mReadMap.put(event.mInventoryBean.getBookBarNo(), event.mInventoryBean);
            queryBookById(event.mInventoryBean.getBookBarNo());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWriteFlagComplete(WriteEvent event) {
        backFinish();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        SerialPortManager.getInstance().stopInventory();
    }

    private void returnBook() {
        if (getActivity() != null && !mSelectedMap.isEmpty()) {
            if (mDialog == null) {
                mDialog = new CommonDialog(getActivity()).loading(getString(R.string.text_loading_return_book));
                mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (mCountDownView != null) {
                            mCountDownView.resume();
                        }
                    }
                });
            }
            mDialog.loading(getString(R.string.text_loading_return_book));
            mDialog.show();
            if (mCountDownView != null) {
                mCountDownView.pause();
            }
            SystemTTS.getInstance().playText("正在还书");
            SerialPortManager.getInstance().stopInventory();
            startReturn();
        } else {
            SystemTTS.getInstance().playText("请先选择图书");
        }
    }

    private void checkIsAll() {
        if (mScanAdapter != null) {
            mCbAll.setChecked(mScanAdapter.getItemCount() == mSelectedMap.size());
        }
        mTvChooseCount.setText(String.format(LanguageUtils.getCurrentLocale(),
                "%s%d%s", getString(R.string.text_had_choose), mSelectedMap.size(), getString(R.string.text_book_unit)));
    }

    private void checkAll(boolean isCheck) {
        mSelectedMap.clear();
        List<QueryBookInfo> list = mScanAdapter.getData();
        for (QueryBookInfo bookBean : list) {
            bookBean.setChecked(isCheck);
            if (isCheck) {
                mSelectedMap.put(bookBean.getBookBarCode(), bookBean);
            }
        }
        if (mScanAdapter != null) {
            mScanAdapter.notifyDataSetChanged();
        }
        mTvChooseCount.setText(String.format(LanguageUtils.getCurrentLocale(),
                "%s%d%s", getString(R.string.text_had_choose), mSelectedMap.size(), getString(R.string.text_book_unit)));
    }

    private void startReturn() {
        if (mDownLatch == null) {
            mDownLatch = new CountDownLatch(mSelectedMap.size());
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mDownLatch.await();
                    //todo 写RFID标志位
                    SerialPortManager.getInstance().backFlag(new ArrayList<>(mReadMap.values()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        for (String bookBarCode : mSelectedMap.keySet()) {
            RxHttp.get(Url.returnBook)
                    .add("BookBarcode", bookBarCode)
                    .asString()
                    .to(RxLife.toMain(this))
                    .subscribe(new Consumer<String>() {
                        @Override
                        public void accept(String result) throws Throwable {
                            Gson gson = new Gson();
                            BorrowResult borrowResult = gson.fromJson(result, BorrowResult.class);
                            InventoryBean bean = mReadMap.get(bookBarCode);
                            if (bean != null) {
                                bean.setSucceed("Y".equals(borrowResult.getBackFlag()));
                            }
                            QueryBookInfo info = mSelectedMap.get(bookBarCode);
                            if (info != null) {
                                info.setBackFlag(borrowResult.getBackFlag());
                                info.setBackInfor(borrowResult.getBackInfor());
                            }
                            mDownLatch.countDown();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Throwable {
                            QueryBookInfo info = mSelectedMap.get(bookBarCode);
                            if (info != null) {
                                info.setBackFlag("N");
                                info.setBackInfor("还书失败");
                            }
                            //  mReadMap.remove(bookBarCode);
                            mDownLatch.countDown();
                        }
                    });
        }
    }

    private void exit() {
        pop();
    }

    private void backFinish() {
        if (mSelectedMap != null && getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                }
            });
            ArrayList<QueryBookInfo> list = new ArrayList<>(mSelectedMap.values());
            startWithPop(ReturnBookDelegate.getInstance(list));
        }
    }


    private void queryBookById(String bookBarCode) {
        RxHttp.get(Url.queryBookByRFID)
                .add("BookBarcode", bookBarCode)
                .asString()
                .to(RxLife.toMain(this))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Throwable {
                        Gson gson = new Gson();
                        ArrayList<QueryBookInfo> list = gson.fromJson(s, new TypeToken<ArrayList<QueryBookInfo>>() {
                        }.getType());
                        if (list != null) {
                            for (QueryBookInfo info : list) {
                                info.setChecked(true);
                                mSelectedMap.put(info.getBookBarCode(), info);
                            }
                            mScanAdapter.addData(list);

                            mTvScanCount.setText(String.format(LanguageUtils.getCurrentLocale(),
                                    "%s%d%s", getString(R.string.text_scan),
                                    mScanAdapter.getData().size(), getString(R.string.text_book_unit)));
                            checkIsAll();
                        }
                        playNoticeOnce();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {

                    }
                });
    }

    private volatile boolean hasPlay = false;

    private void playNoticeOnce() {
        if (!hasPlay && mScanAdapter.getData().size() > 0) {
            hasPlay = true;
            SystemTTS.getInstance().playText("请先确认图书，并点击还书");
        }
    }
}